# -*- coding: utf-8 -*-

import datetime
import base64
import json
import time
from celery.schedules import crontab
from celery.task import periodic_task
from common.log import logger
from blueking.component.shortcuts import get_client_by_request, get_client_by_user

from demo.models import Host, HostStat

cmd = """
#!/bin/bash
MEMORY=$(free -m | awk 'NR==2{printf "%.2f%%", $3*100/$2 }')
DISK=$(df -h | awk '$NF=="/"{printf "%s", $5}')
CPU=$(top -bn1 | grep load | awk '{printf "%.2f%%", $(NF-2)}')
DATE=$(date "+%Y-%m-%d %H:%M:%S")
echo -e "$DATE|$MEMORY|$DISK|$CPU"
"""


@periodic_task(run_every=crontab(minute='*/1', hour='*', day_of_week="*"))
def monitor_host_stat():
    bizs = Host.objects.values('bk_biz_id').distinct()
    content = base64.b64encode(cmd)

    for biz in bizs:
        bk_biz_id = biz["bk_biz_id"]
        ips = Host.objects.filter(bk_biz_id=bk_biz_id).values('ip').distinct()
        ip_list = []
        for ip in ips:
            ip_list.append(dict(ip=ip["ip"], bk_cloud_id=0))

        args = {"bk_biz_id": bk_biz_id,
                "ip_list": ip_list,
                "account": "root",
                "script_content": content}
        client = get_client_by_user("admin")
        job_id = client.job.fast_execute_script(args)['data']['job_instance_id']

        status_args = {"bk_biz_id": bk_biz_id, "job_instance_id": job_id}
        while True:
            is_finished = client.job.get_job_instance_status(status_args)['data']['is_finished']
            if is_finished:
                break
            time.sleep(0.5)
        response = client.job.get_job_instance_log(status_args)
        if response["result"]:
            results = response["data"][0]['step_results'][0]['ip_logs']
            for result in results:
                stat = result["log_content"].replace('%', '').split('|')
                host_stat = HostStat(bk_biz_id=bk_biz_id,
                                     ip=result["ip"],
                                     monitor_time=stat[0],
                                     mem=float(stat[1]),
                                     disk=float(stat[2]),
                                     cpu=float(stat[3]))
                host_stat.save()

    now = datetime.datetime.now()
    logger.info(u"celery 周期任务调用成功，当前时间：{}".format(now))
